﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using Infrastructure.Utilities;

namespace LuckyDraw.WinUI
{
	public partial class MainForm : Form
	{
		private DesignerSetting defaultSetting = null;
		private bool drawing = false;
		private List<DrawPeople> EntityList = null;

		public MainForm()
		{
			InitializeComponent();
			this.Load += Form1_Load;
		}

		void Form1_Load(object sender, EventArgs e)
		{
			this.Shown += MainForm_Shown;
			btnImport.Click += btnImport_Click;
			btnDraw.Click += btnDraw_Click;
			btnSaveResult.Click += btnSaveResult_Click;
			btnRemove.Click += btnRemove_Click;
			btnSetting.Click += btnSetting_Click;
			btnDrawPeopleBrowser.Click += btnDrawPeopleBrowser_Click;
			btnResetResult.Click += btnResetResult_Click;
			comboBox1.SelectedIndexChanged += comboBox1_SelectedIndexChanged;

			DB.CreateDB();
			LoadWinning();
			InitPrizeType();
		}

		void MainForm_Shown(object sender, EventArgs e)
		{
			DefaultLayout();
			DynamicLayout();
		}

		private void Draw() //抽奖。
		{
			if (this.EntityList == null)
			{
				return;
			}

			while (drawing)
			{
				foreach (DrawPeople entity in EntityList)
				{
					if (this.IsDisposed)
					{
						break;
					}

					if (!drawing)
					{
						break;
					}

					try
					{
						this.Invoke(new EventHandler(delegate
						{
							lblCouponNo.Text = entity.CouponNo;
							lblCouponNo.Tag = entity;
						}));
					}
					catch
					{
					}

					int n = new Random((int)DateTime.Now.Ticks).Next(1, 9) * 10;
					Thread.Sleep(n);
				}
			}

			this.Invoke(new EventHandler(delegate
			{
				DrawPeople winning = lblCouponNo.Tag as DrawPeople;
				winning.Result = comboBox1.Text;

				DB.UpdateResult(winning);

				listBox1.Items.Add(winning);
			}));
		}

		void btnDraw_Click(object sender, EventArgs e)
		{
			if (drawing)
			{
				btnDraw.Text = "开始抽奖";
				drawing = false;
			}
			else
			{
				this.EntityList = DB.SelectDrawPeople();

				List<Strategy> strategyList = DB.SelectStrategy();
				Strategy strategy = strategyList.FirstOrDefault(a => a.Name == comboBox1.Text);
				if (strategy != null) //如果指定了中奖次数；
				{
					int cnt = EntityList.Count(a => a.Result == comboBox1.Text);
					if (cnt >= strategy.Number) //如果已经达到中奖次数；
					{
						MessageBox.Show("{0} 已达到中奖次数，请换一种抽奖类型".Fmt(comboBox1.Text), "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
						return;
					}
				}

				EntityList = EntityList.Select(a => new
				{
					a,
					newID = Guid.NewGuid()
				}).OrderBy(b => b.newID).Select(c => c.a).ToList();

				this.EntityList = this.EntityList.Where(a => a.Result.IsNullOrEmpty()).ToList(); //已经抽中奖的劵不再重复参与抽奖。

				if (!comboBox1.Text.IsNullOrEmpty())
				{
					this.EntityList = this.EntityList.Where(a =>
						a.PrizeType1 == comboBox1.Text ||
						a.PrizeType2 == comboBox1.Text ||
						a.PrizeType3 == comboBox1.Text ||
						a.PrizeType4 == comboBox1.Text ||
						a.PrizeType5 == comboBox1.Text)
						.ToList();
				}

				if (!this.EntityList.Any())
				{
					lblCouponNo.Text = "抽奖完毕";
					lblCouponNo.Tag = null;
					return;
				}

				btnDraw.Text = "　停止　";

				drawing = true;
				ThreadPool.QueueUserWorkItem(s =>
				{
					Draw();
				});
			}
		}

		void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
		{
			btnDraw.Text = "开始抽奖";
			drawing = false;

			LoadWinning();
		}

		void btnImport_Click(object sender, EventArgs e)
		{
			List<DrawPeople> entities = ReadExcel();
			DB.InsertDrawPeople(entities);

			LoadWinning();
			InitPrizeType();
		}

		private void InitPrizeType()
		{
			comboBox1.Items.Clear();
			foreach (string item in DB.SelectPrizeType())
			{
				comboBox1.Items.Add(item);
			}

			if (comboBox1.Items.Count > 0)
			{
				comboBox1.SelectedIndex = 0;
			}
		}

		private List<DrawPeople> ReadExcel()
		{
			if (openFileDialog1.ShowDialog() != DialogResult.OK)
			{
				return null;
			}

			List<DrawPeople> entities = new List<DrawPeople>();
			try
			{
				entities = ExcelHelper.Read<DrawPeople>(openFileDialog1.FileName, "Sheet1");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}

			return entities;
		}

		private void LoadWinning()
		{
			listBox1.Items.Clear();

			List<DrawPeople> list = DB.SelectDrawPeople();

			if (checkBox1.Checked)
			{
				list = list.Where(a => a.Result == comboBox1.Text).ToList();
			}

			foreach (DrawPeople entity in list)
			{
				if (!entity.Result.IsNullOrEmpty() && entity.Result != "缺席")
				{
					listBox1.Items.Add(entity);
				}
			}
		}

		void btnSaveResult_Click(object sender, EventArgs e)
		{
			string text = "";
			foreach (DrawPeople entity in listBox1.Items)
			{
				text += entity.ToString() + "\r\n";
			}

			saveFileDialog1.FileName = "抽奖结果.txt";
			if (saveFileDialog1.ShowDialog() == DialogResult.OK)
			{
				File.WriteAllText(saveFileDialog1.FileName, text);
			}
		}

		void btnRemove_Click(object sender, EventArgs e)
		{
			InputBoxForm form = new InputBoxForm();
			if (form.ShowDialog() != DialogResult.OK)
			{
				return;
			}

			foreach (object obj in listBox1.Items)
			{
				if ((obj as DrawPeople).CouponNo == form.CouponNo)
				{
					DB.Absent(form.CouponNo);
					listBox1.Items.Remove(obj);
					break;
				}
			}

		}

		void btnSetting_Click(object sender, EventArgs e)
		{
			SettingForm form = new SettingForm();
			form.DefaultSetting = defaultSetting;
			if (form.ShowDialog() != DialogResult.OK)
			{
				return;
			}

			DynamicLayout();
		}

		private void DefaultLayout()
		{
			defaultSetting = new DesignerSetting()
			{
				LogoWidht = 200,
				LogoHeight = 200,

				CouponNoX = lblCouponNo.Left,
				CouponNoY = lblCouponNo.Top,
				CouponNoFontName = lblCouponNo.Font.Name,
				CouponNoFontSize = lblCouponNo.Font.Size,
				CouponNoForeColor = lblCouponNo.ForeColor.Name,

				DrawButtonX = btnDraw.Left,
				DrawButtonY = btnDraw.Top,
				DrawButtonFontName = btnDraw.Font.Name,
				DrawButtonFontSize = btnDraw.Font.Size,
				DrawButtonForeColor = btnDraw.ForeColor.Name,

				PrizeTypeLabelX = lblPrizeType.Left,
				PrizeTypeLabelY = lblPrizeType.Top,
				PrizeTypeLabelFontName = lblPrizeType.Font.Name,
				PrizeTypeLabelFontSize = lblPrizeType.Font.Size,
				PrizeTypeLabelForeColor = lblPrizeType.ForeColor.Name,
				PrizeTypeLabelVisual = lblPrizeType.Visible,

				PrizeTypeComboX = comboBox1.Left,
				PrizeTypeComboY = comboBox1.Top,
				PrizeTypeComboFontName = comboBox1.Font.Name,
				PrizeTypeComboFontSize = comboBox1.Font.Size,

				WinningX = listBox1.Left,
				WinningY = listBox1.Top,
				WinningFontName = listBox1.Font.Name,
				WinningFontSize = listBox1.Font.Size,
				WinningForeColor = listBox1.ForeColor.Name,
				WinningHeight = listBox1.Height,
				WinningWidth = listBox1.Width,

				WinningLabelX = lblWinningTitle.Left,
				WinningLabelY = lblWinningTitle.Top,
				WinningLabelFontName = lblWinningTitle.Font.Name,
				WinningLabelFontSize = lblWinningTitle.Font.Size,
				WinningLabelForeColor = lblWinningTitle.ForeColor.Name,
			};
		}

		private void DynamicLayout()
		{
			DesignerSetting setting = DesignerSetting.Load();
			if (setting == null)
			{
				return;
			}

			if (setting.BackgroundImage.IsNullOrEmpty())
			{
				this.BackgroundImage = global::LuckyDraw.WinUI.Properties.Resources.底图1;
			}
			else
			{
				try
				{
					Image image = Bitmap.FromFile(setting.BackgroundImage);
					this.BackgroundImage = image;
				}
				catch
				{
				}
			}

			if (setting.LogoImage.IsNullOrEmpty())
			{
				pictureBox1.Image = global::LuckyDraw.WinUI.Properties.Resources.幸运大抽奖;
			}
			else
			{
				try
				{
					Image image = Bitmap.FromFile(setting.LogoImage);
					pictureBox1.Image = image;
				}
				catch
				{
				}
			}

			pictureBox1.Left = (this.Width - pictureBox1.Width) / 2;
			pictureBox1.Top = 12;
			pictureBox1.Width = setting.LogoWidht == 0 ? pictureBox1.Width : setting.LogoWidht;
			pictureBox1.Height = setting.LogoHeight == 0 ? pictureBox1.Height : setting.LogoHeight;

			lblCouponNo.Location = new Point(setting.CouponNoX, setting.CouponNoY);
			lblCouponNo.Font = new Font(setting.CouponNoFontName, setting.CouponNoFontSize == 0 ? lblCouponNo.Font.Size : setting.CouponNoFontSize, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
			lblCouponNo.ForeColor = Color.FromName(setting.CouponNoForeColor.IsNullOrEmpty() ? lblCouponNo.ForeColor.Name : setting.CouponNoForeColor);

			btnDraw.Location = new Point(setting.DrawButtonX, setting.DrawButtonY);
			btnDraw.Font = new Font(setting.DrawButtonFontName, setting.DrawButtonFontSize == 0 ? btnDraw.Font.Size : setting.DrawButtonFontSize, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
			btnDraw.ForeColor = Color.FromName(setting.DrawButtonForeColor.IsNullOrEmpty() ? btnDraw.ForeColor.Name : setting.DrawButtonForeColor);

			lblPrizeType.Location = new Point(setting.PrizeTypeLabelX, setting.PrizeTypeLabelY);
			lblPrizeType.Font = new Font(setting.PrizeTypeLabelFontName, setting.PrizeTypeLabelFontSize == 0 ? lblPrizeType.Font.Size : setting.PrizeTypeLabelFontSize, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
			lblPrizeType.ForeColor = Color.FromName(setting.PrizeTypeLabelForeColor.IsNullOrEmpty() ? lblPrizeType.ForeColor.Name : setting.PrizeTypeLabelForeColor);
			lblPrizeType.Visible = setting.PrizeTypeLabelVisual;

			comboBox1.Location = new Point(setting.PrizeTypeComboX, setting.PrizeTypeComboY);
			comboBox1.Font = new Font(setting.PrizeTypeComboFontName, setting.PrizeTypeComboFontSize == 0 ? comboBox1.Font.Size : setting.PrizeTypeComboFontSize, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));

			listBox1.Location = new Point(setting.WinningX, setting.WinningY);
			listBox1.Size = new Size(setting.WinningWidth, setting.WinningHeight);
			listBox1.Font = new Font(setting.WinningFontName, setting.WinningFontSize == 0 ? listBox1.Font.Size : setting.WinningFontSize, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
			listBox1.ForeColor = Color.FromName(setting.WinningForeColor.IsNullOrEmpty() ? listBox1.ForeColor.Name : setting.WinningForeColor);

			lblWinningTitle.Location = new Point(setting.WinningLabelX, setting.WinningLabelY);
			lblWinningTitle.Font = new Font(setting.WinningLabelFontName, setting.WinningLabelFontSize == 0 ? lblWinningTitle.Font.Size : setting.WinningLabelFontSize, FontStyle.Bold, GraphicsUnit.Point, ((byte)(134)));
			lblWinningTitle.ForeColor = Color.FromName(setting.WinningLabelForeColor.IsNullOrEmpty() ? lblWinningTitle.ForeColor.Name : setting.WinningLabelForeColor);
		}

		void btnDrawPeopleBrowser_Click(object sender, EventArgs e)
		{
			DrawPeopleForm form = new DrawPeopleForm();
			form.ShowDialog();
		}

		void btnResetResult_Click(object sender, EventArgs e)
		{
			if (comboBox1.Text.IsNullOrEmpty())
			{
				return;
			}

			if (MessageBox.Show("重置抽奖结果后，将清除 {0}  的抽奖名单，您确定要重置 {0} 的抽奖结果？".Fmt(comboBox1.Text), "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
			{
				return;
			}

			DB.ResetResult(comboBox1.Text);
			LoadWinning();
		}
	}
}
